package net.zjitc.controller;

import net.zjitc.pojo.User;
import net.zjitc.service.AdminUserService;
import net.zjitc.service.UserService;
import net.zjitc.service.impl.AdminUserServiceImpl;
import net.zjitc.service.impl.UserServiceImpl;
import net.zjitc.utils.dispacher.URLMapping;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * Created by Administrator on 2017/11/22.
 */
public class AdminUser {
    UserService userService = new UserServiceImpl();

    @URLMapping(url = "/findAllUser")
    public String findAll(HttpServletRequest request, HttpServletResponse response) {
        UserService userService = new UserServiceImpl();
        List<User> list = userService.findAll();
        request.setAttribute("list", list);
        return "/admin/user/list.jsp";
    }

    @URLMapping(url = "/loginUI")
    public String loginUI(HttpServletRequest request, HttpServletResponse response) {

        return "/WEB-INF/user/login.jsp";
    }

    @URLMapping(url = "/registUI")
    public String registUI(HttpServletRequest request, HttpServletResponse response) {
        return "/WEB-INF/user/regist.jsp";
    }

    @URLMapping(url = "/regist")
    public String regist(HttpServletRequest request, HttpServletResponse response) {
        String inputCode = request.getParameter("code");
        String trueCode = (String) request.getSession().getAttribute("validateCode");
        if (!inputCode.equalsIgnoreCase(trueCode)) {
            request.setAttribute("codeMsg", "验证码错误");
            return "/WEB-INF/user/regist.jsp";
        }
        User user = new User();
        try {
            BeanUtils.populate(user, request.getParameterMap());
            int count = userService.save(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.setAttribute("msg", "请先去激活，在登录");
        return "/WEB-INF/user/msg.jsp";
    }

    @URLMapping(url = "/activeCode")
    public String activeCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String code = request.getParameter("code");

        User user = userService.findByCode(code);
        if (user != null) {
            user.setCode(null);
            user.setState(1);
            int count = userService.update(user);
            request.setAttribute("msg", "激活成功,请登录");
        } else {
            request.setAttribute("msg", "激活失败,请登录");
        }
        //response.getWriter().print("激活成功");
        //查询用户
        //User user=userService.findCode(code);
        //user.setState(1);
        //userService.update(user);
     return "/WEB-INF/user/msg.jsp";
    }
}
